package me.teacms.service.impl;

import me.teacms.common.result.JsonResult;
import me.teacms.dao.ArticleNewDao;
import me.teacms.entity.ArticleCategory;
import me.teacms.entity.ArticleTag;
import me.teacms.entity.Category;
import me.teacms.entity.Tag;
import me.teacms.entity.vo.ArticleNewVo;
import me.teacms.service.ArticleNewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: XiaoBingBy
 * Email: XiaoBingBy@qq.com
 * Date: 2017/2/22
 * Time: 16:43
 * Describe: 添加文章业务 实现
 */
@Service
public class ArticleNewServiceImpl implements ArticleNewService {

    @Autowired
    private ArticleNewDao articleNewDao;

    /**
     * 添加文章
     *
     * @param articleNewVo
     * @return
     */
    @Override
    public JsonResult addArticle(ArticleNewVo articleNewVo) {

        /**
         * 插入文章
         */
        int addArticleState = articleNewDao.addArticle(articleNewVo);

        /**
         *
         */

        /**
         * 插入文章分类
         */
        List<ArticleCategory> articleCategories = articleNewVo.getArticleCategories();
        if (articleCategories == null) {
            ArticleCategory item = new ArticleCategory();
            item.setArticleId(articleNewVo.getId());
            item.setCategoryId(1);
            ArrayList<ArticleCategory> temp = new ArrayList<>();
            temp.add(item);
            int addArticleCategoryState = articleNewDao.addArticleCategory(temp);
        } else {
            List<ArticleCategory> articleCategoryNews = new ArrayList<ArticleCategory>();
            for (ArticleCategory item : articleCategories) {
                if (item.getCategoryId() != null) {
                    item.setArticleId(articleNewVo.getId());
                    articleCategoryNews.add(item);
                }
            }
            int addArticleCategoryState = articleNewDao.addArticleCategory(articleCategoryNews);
        }


        /**
         * 插入文章标签
         */
        List<ArticleTag> articleTags = articleNewVo.getArticleTags();
        if (articleTags != null) {
            ArrayList<ArticleTag> articleTagsNews = new ArrayList<>();
            for (ArticleTag item : articleTags) {
                if (item.getTagId() != null) {
                    item.setArticleId(articleNewVo.getId());
                    articleTagsNews.add(item);
                }
            }
            int addArticleTagState = articleNewDao.addArticleTag(articleTagsNews);
        }

        /**
         * 判断是否插入成功
         */
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(true);
        jsonResult.setMsg("文章内容发布成功!");

        return jsonResult;
    }
}
